//
//  YnuDanBatchPaiDViewController.m
//  NtoccDriverNew
//
//  Created by 张天兴 on 2023/3/19.
//  Copyright © 2023 GCY. All rights reserved.
//

#import "YnuDanBatchPaiDViewController.h"
#import "YunDanBatchPaiDanCell.h"
#import "PaiDanXuanZeSJController.h"

@interface YnuDanBatchPaiDViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong , nonatomic)UITableView *tableView;

@property (strong, nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UIView* bgView;

@property (nonatomic, strong) UIView* erwmView;

@property (nonatomic, strong) UIImageView *erwmImagView;

@property (nonatomic, strong) UILabel *infroLabel;

@property (nonatomic, strong) UILabel *zhAddLabel;

@property (nonatomic, strong) UILabel *zhDetileAddLabel;

@property (nonatomic, strong) UILabel *xhAddLabel;

@property (nonatomic, strong) UILabel *xhDetileAddLabel;

@property (nonatomic, strong) UILabel *zhStateTime;

@property (nonatomic, strong) UILabel *xhEndTime;

@property (nonatomic, strong) UITapGestureRecognizer *changeVoidceSet;

@property (nonatomic, strong) UIButton *buttonImag;

@property (nonatomic, strong) NSMutableArray *titAddArr;

@end

@implementation YnuDanBatchPaiDViewController

- (void)viewDidAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.dataArray removeAllObjects];
    [self loadNewData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BackgroundColor;
    self.navigationItem.title = @"批量派单";
    _pageNum = 1;
    self.dataArray = [NSMutableArray array];
    [self setupBaseView];
    [self yunDanBatchListRequest];
}






-  (void)setupBaseView{
    [self.view addSubview:self.tableView];

}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BackgroundColor;
        _tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NavHeight - MenuBarHeight);
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:@"YunDanBatchPaiDanCell" bundle:nil] forCellReuseIdentifier:@"YunDanBatchPaiDanCell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}
-(UIView *)bgView{
    if (!_bgView) {
        self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
        self.bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        self.changeVoidceSet = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeVoidceSet:)];
        [self.bgView addGestureRecognizer:self.changeVoidceSet];
    }
    return _bgView;
}
- (UIView *)erwmView{
    if (!_erwmView) {
        self.erwmView = [[UIView alloc] initWithFrame:CGRectMake(20, (ScreenH - ScreenW - 20)/2, ScreenW - 40, ScreenW - 20)];
        self.erwmView.backgroundColor = [UIColor whiteColor];
        [self.erwmView addSubview:self.infroLabel];
        [self.erwmView addSubview:self.zhAddLabel];
        [self.erwmView addSubview:self.zhDetileAddLabel];
        [self.erwmView addSubview:self.xhAddLabel];
        [self.erwmView addSubview:self.xhDetileAddLabel];
        [self.erwmView addSubview:self.zhStateTime];
        [self.erwmView addSubview:self.xhEndTime];
        self.erwmView.layer.masksToBounds = YES;
        self.erwmView.layer.cornerRadius = 10;
    }
    return _erwmView;
}
- (UILabel *)infroLabel{
    if(!_infroLabel){
        self.infroLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, ScreenW - 55, 20)];
        self.infroLabel.textColor = Light_TextColor;
        self.infroLabel.font = [UIFont systemFontOfSize:15];
    }
    return _infroLabel;
}
- (UILabel *)zhAddLabel{
    if(!_zhAddLabel){
        self.zhAddLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.infroLabel.frame) + 5, ScreenW - 55, 20)];
        self.zhAddLabel.textColor = Light_TextColor;
        self.zhAddLabel.font = [UIFont systemFontOfSize:15];
    }
    return _zhAddLabel;
}
- (UILabel *)zhDetileAddLabel{
    if(!_zhDetileAddLabel){
        self.zhDetileAddLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.zhAddLabel.frame) + 5, ScreenW - 55, 20)];
        self.zhDetileAddLabel.textColor = Light_TextColor;
        self.zhDetileAddLabel.font = [UIFont systemFontOfSize:15];
    }
    return _zhDetileAddLabel;
}
- (UILabel *)xhAddLabel{
    if(!_xhAddLabel){
        self.xhAddLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.zhDetileAddLabel.frame) + 5, ScreenW - 55, 20)];
        self.xhAddLabel.textColor = Light_TextColor;
        self.xhAddLabel.font = [UIFont systemFontOfSize:15];
    }
    return _xhAddLabel;
}
- (UILabel *)xhDetileAddLabel{
    if(!_xhDetileAddLabel){
        self.xhDetileAddLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.xhAddLabel.frame) + 5, ScreenW - 55, 20)];
        self.xhDetileAddLabel.textColor = Light_TextColor;
        self.xhDetileAddLabel.font = [UIFont systemFontOfSize:15];
    }
    return _xhDetileAddLabel;
}
- (UILabel *)zhStateTime{
    if(!_zhStateTime){
        self.zhStateTime = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.xhDetileAddLabel.frame) + 5, ScreenW - 55, 20)];
        self.zhStateTime.textColor = Light_TextColor;
        self.zhStateTime.font = [UIFont systemFontOfSize:15];
    }
    return _zhStateTime;
}
- (UILabel *)xhEndTime{
    if(!_xhEndTime){
        self.xhEndTime = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.zhStateTime.frame) + 5, ScreenW - 55, 20)];
        self.xhEndTime.textColor = Light_TextColor;
        self.xhEndTime.font = [UIFont systemFontOfSize:15];
    }
    return _xhEndTime;
}
- (UIImageView *)erwmImagView{
    if (!_erwmImagView) {
        self.erwmImagView = [[UIImageView alloc] initWithFrame:CGRectMake(((ScreenW - 40) - (ScreenW -220))/2 , (ScreenW - 40) - (ScreenW - 220), ScreenW -220, ScreenW - 220)];
//        self.erwmImagView.backgroundColor = [UIColor redColor];
    }
    return _erwmImagView;
}
-(UIButton *)buttonImag{
    if (!_buttonImag) {
        self.buttonImag = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [self.buttonImag setTitle:@"保存图片" forState:(UIControlStateNormal)];
        self.buttonImag.backgroundColor = Green_Color;
        [self.buttonImag setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        self.buttonImag.frame = CGRectMake(20,CGRectGetMaxY(self.erwmView.frame) + 10, ScreenW - 40, 44);
        self.buttonImag.layer.masksToBounds = YES;
        self.buttonImag.layer.cornerRadius = 22;
        [self.buttonImag addTarget:self action:@selector(buttonImagAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _buttonImag;
}
- (void)changeVoidceSet:(UITapGestureRecognizer *)sender{
    if(CGRectContainsPoint(self.erwmView.frame, [sender locationInView:self.bgView])){

    }else{
            [self.bgView removeFromSuperview];
    }

}
- (void)buttonImagAction{
        [self.bgView removeFromSuperview];
    //把view生成图片保存
    UIImageWriteToSavedPhotosAlbum([self convertViewToImage:self.erwmView], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

}

- (void)loadNewData{
    self.pageNum = 1;
    [self yunDanBatchListRequest];
}
- (void)loadMoreData{
    self.pageNum ++;
    [self yunDanBatchListRequest];
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 190, 190)];
        _foundImageView.image = image(@"gcy_img_not_found");
        _foundImageView.contentMode = UIViewContentModeCenter;
        _foundImageView.center = self.view.center;
        _foundImageView.cy_y -=80;
        UILabel *textL = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, 190, 20)];
        textL.text = @"暂无数据";
        textL.textAlignment = NSTextAlignmentCenter;
        textL.textColor = [UIColor colorWithHexString:@"#ADB6CC"];
        textL.font = [UIFont systemFontOfSize:12.0f];
        [_foundImageView addSubview:textL];
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

#pragma mark - UITableViewDelegate

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    YunDanBatchPaiDanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YunDanBatchPaiDanCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    pinLiangYunDanModel *model = self.dataArray[indexPath.row];
    [cell.erweimaButton addTarget:self action:@selector(erweimaButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.piliangButton addTarget:self action:@selector(piLiangButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    if (self.dataArray.count != 0) {
        [cell assignmentYunDanBatchPaiDancell:model];
    }
    
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 220;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PaiDanXuanZeSJController * PaiVCC = [[PaiDanXuanZeSJController alloc] init];
    pinLiangYunDanModel *model = self.dataArray[indexPath.row];
    PaiVCC.branchCode = self.createdBy;
    PaiVCC.driverIsShare = @"0";
    PaiVCC.infoFee = @"0";
    PaiVCC.status = 0;
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *str in model.sonCodes) {
        [arr addObject:str];
    }
    PaiVCC.orderArr = arr;
    PaiVCC.paiDanType = 0;
    [self.navigationController pushViewController:PaiVCC animated:NO];
}
- (void)piLiangButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    PaiDanXuanZeSJController * PaiVCC = [[PaiDanXuanZeSJController alloc] init];
    pinLiangYunDanModel *model = self.dataArray[indexpath.row];
    PaiVCC.branchCode = self.createdBy;
    PaiVCC.driverIsShare = @"0";
    PaiVCC.infoFee = @"0";
    PaiVCC.status = 0;
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *str in model.sonCodes) {
        [arr addObject:str];
    }
    PaiVCC.orderArr = arr;
    PaiVCC.paiDanType = 0;
    [self.navigationController pushViewController:PaiVCC animated:NO];
}
- (void)yunDanBatchListRequest{
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params = [NSDictionary dictionary];
    
        params = @{
            @"pageNum": [NSNumber numberWithInteger:_pageNum],
            @"pageSize": DEFULT_LOAD_NUM,
            @"partyCode": self.createdBy,
        };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],ORDER_ALL_BIGORFER) withParameter:params
                            withVC:self netName:@"我的运单中心" success:^(id response, NSString *msg) {
        if ([response count] != 0) {
            
            [weakSelf.dataArray addObjectsFromArray:[pinLiangYunDanModel mj_objectArrayWithKeyValuesArray:response]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
//                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}
- (void)erweimaButton:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    [[UIApplication sharedApplication].keyWindow  addSubview:self.bgView];
    [self.bgView addSubview:self.erwmView];
    [self.erwmView addSubview:self.erwmImagView];
    [self.bgView addSubview:self.buttonImag];
    pinLiangYunDanModel *model = self.dataArray[indexpath.row];
    [self NetworkReweima:model.code];
    self.titAddArr = [NSMutableArray array];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.coalTypeName)];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.shipperAddress)];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.shipperDetailAddress)];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.consigneeAddress)];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.consigneeDetailAddress)];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.lastLoadingTime)];
    [self.titAddArr addObject:CJStringWithFormat(@"%@",model.lastUnloadingTime)];
    self.infroLabel.attributedText = [self stringColorStr:@"货物信息:" String:self.titAddArr.firstObject Color:[UIColor blueColor]];
    self.zhAddLabel.attributedText = [self stringColorStr:@"装货市区:" String:self.titAddArr[1] Color:[UIColor blueColor]];
    self.zhDetileAddLabel.attributedText = [self stringColorStr:@"详细地址:" String:self.titAddArr[2] Color:[UIColor blueColor]];
    self.xhAddLabel.attributedText = [self stringColorStr:@"卸货市区:" String:self.titAddArr[3] Color:[UIColor blueColor]];
    self.xhDetileAddLabel.attributedText = [self stringColorStr:@"详细地址:" String:self.titAddArr[4] Color:[UIColor blueColor]];
    self.zhStateTime.attributedText = [self stringColorStr:@"装车时间:" String:self.titAddArr[5] Color:[UIColor blueColor]];
    self.xhEndTime.attributedText = [self stringColorStr:@"卸货时间:" String:self.titAddArr.lastObject Color:[UIColor blueColor]];

}
- (void)NetworkReweima:(NSString *)codID{
    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-test-api",[ReAddressDynamic shared].baseUrl],QRTAKEORDER_TWSTTOANDROID);
    NSDictionary *params = @{@"mainOrderCode": codID,@"tempCode":self.createdBy};
    [HTTPManager getNetworkRequest:urlStr withParameter:params withVC:nil netName:@"批量派单二维码获取" success:^(id response, NSString *msg) {
        NSData* data = [[NSData alloc] initWithBase64EncodedString:response options:0];
        
        self.erwmImagView.image = [UIImage imageWithData:data];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
    if (error) {
        [XSInfoView showInfo:@"保存失败" onView:self.view];
        [self.bgView removeFromSuperview];
    } else {
        [XSInfoView showInfo:@"保存成功" onView:self.view];
        [self.bgView removeFromSuperview];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSMutableAttributedString *)stringColorStr:(NSString *)str String:(NSString *)string Color:(UIColor*)color{
    //Label不同字显示不同颜色
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",str,string]];
    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:string].location, [[noteStr string] rangeOfString:string].length);
    //需要设置的位置
    [noteStr addAttribute:NSForegroundColorAttributeName value:color range:redRange];
    return noteStr;
}
- (UIImage*)convertViewToImage:(UIView*)v{
    CGSize s = v.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
@end
